<template>
  <AppDialogForm
    :title="props.attrInfo !== null ? '编辑' : '添加' + titleText"
    :confirm="handleSubmit"
    @closed="handleDialogClosed"
    @open="handleDialogOpen"
  >
    <el-form
      ref="form"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="loading"
    >
      <el-form-item :label="titleText" prop="attr_name">
        <el-input v-model="formData.attr_name" />
      </el-form-item>
    </el-form>
  </AppDialogForm>
</template>

<script setup>
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { addParams, editParams } from "@/api/params.js";

const props = defineProps({
  attrInfo: {
    type: Object,
    default: () => {},
  },
  titleText: {
    type: String,
    default: "",
  },
  activeTabName: {
    type: String,
    default: "",
  },
  cateId: {
    type: Number,
    default: null,
  },
});
const emit = defineEmits(["success"]);
const form = ref(null);
const loading = ref(false);
const formData = ref({
  attr_name: "",
});
const formRules = {
  attr_name: [{ required: true, message: "请输入参数名称", trigger: "blur" }],
};

const loadInfo = () => {
  if (!props.attrInfo) {
    return;
  }
  formData.value = { ...props.attrInfo };
};

const handleDialogOpen = () => {
  loadInfo();
};

const handleSubmit = async () => {
  const valid = await form.value.validate();
  if (!valid) {
    return;
  }
  loading.value = true;
  if (props.attrInfo !== null) {
    // 更新
    await editParams(props.cateId, formData.value).finally(() => {
      loading.value = false;
    });
    ElMessage.success("编辑成功");
  } else {
    const data = {
      attr_name: formData.value.attr_name,
      attr_sel: props.activeTabName,
    };
    // 添加
    await addParams(props.cateId, data).finally(() => {
      loading.value = false;
    });
    ElMessage.success("添加成功");
  }
  emit("success");
};
const handleDialogClosed = () => {
  form.value.clearValidate(); // 清除验证结果
  form.value.resetFields(); // 清除表单数据
  formData.value = {
    attr_name: "",
  };
};
</script>

<style lang="scss" scoped></style>
